package com.demo1221.demo02.listerner;

import com.demo1221.demo02.entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.LinkedHashMap;
import java.util.Map;
//@WebListener
public class OnlineListerner implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (event.getName().equals("user")) {
            Map<String, User> onlineUser = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUser");
            if (onlineUser == null) {
                onlineUser = new LinkedHashMap<String, User>();
            }
            User user = (User) event.getValue();
            onlineUser.put(user.getName(), user);
            event.getSession().getServletContext().setAttribute("onlineUser", onlineUser);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (event.getName().equals("user")) {
            Map<String, User> onlineUser = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUser");
            if (onlineUser != null) {
                User user = (User) event.getValue();
                onlineUser.remove(user.getName());
                event.getSession().getServletContext().setAttribute("onlineUser", onlineUser);
            }
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        if (event.getName().equals("user")) {
            Map<String, User> onlineUser = (Map<String, User>) event.getSession().getServletContext().getAttribute("onlineUser");
            if (onlineUser == null) {
                onlineUser = new LinkedHashMap<String, User>();
            }
            User oldUser = (User) event.getValue();
            onlineUser.remove(oldUser.getName());
            User newUser = (User) event.getSession().getAttribute("user");
            onlineUser.put(newUser.getName(), newUser);
            event.getSession().getServletContext().setAttribute("onlineUser", onlineUser);
        }
    }

}
